package com.ecsolutions.Validators;

import com.ecsolutions.dao.ChangePwd_DAO;
import com.ecsolutions.entity.ChangePwd_Entity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * Created by Administrator on 2017/8/11.
 */
@Component
public class ChangePwdValidate implements Validator {
    private ChangePwd_DAO changePwd_dao;
    @Autowired
    public ChangePwdValidate(ChangePwd_DAO changePwd_dao) {
        this.changePwd_dao = changePwd_dao;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return ChangePwd_Entity.class.isAssignableFrom(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        ChangePwd_Entity form =(ChangePwd_Entity) target;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "OldPassword", "amountrequired", "旧密码不能为空");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "NewPassword", "amountrequired", "新密码不能为空");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "NewPassword2", "amountrequired", "确认新密码不能为空");


       if (!(form.getOldPassword().isEmpty())){
            if(!(changePwd_dao.getPassword(form.getUserID()).equals(form.getOldPassword()))){
                errors.rejectValue("OldPassword","ddd","密码输入错误");
            }
        }
        if( !(form.getNewPassword().isEmpty() || form.getNewPassword2().isEmpty())) {
            if(!(form.getNewPassword().equals(form.getNewPassword2()))){
                errors.rejectValue("NewPassword2","ddd","确认新密码必须和密码相同");
            }
        }
    }


}
